﻿using SAD_Assignment1.BLO;
using SAD_Assignment1.DTO;
using SAD_Assignment1.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SAD_Assignment1.Admin
{
    public partial class AccountDetail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["account"] == null)
            {
                Response.Redirect(Resource.Login);
                return;
            }
            AccountDTO accDTO = (AccountDTO)Session["account"];
            if (!"admin".Equals(accDTO.Roles))
            {
                Response.Redirect(Resource.Login);
                return;
            }
            if (!IsPostBack)
            {
                if (Request.Params["ID"] != null)
                {
                    initComponent();
                }
            }
        }

        private void initComponent()
        {
            int accID = 0;
            try { accID = Int32.Parse(Request.Params["ID"]); }
            catch (Exception) { }
            AccountBLO accBLO = new AccountBLO();
            AccountDTO accDTO = accBLO.getAccountByID(accID);
            if (accDTO == null)
            {
                Response.Redirect(Resource.Error);
                return;
            }
            txtID.Text = accDTO.ID.ToString();
            txtEmail.Text = accDTO.Email;
            txtName.Text = accDTO.Name;
            txtPass.Attributes.Add("value", accDTO.Password);
            txtConfirm.Attributes.Add("value", accDTO.Password);
            ddlRoles.SelectedValue = accDTO.Roles;
            SubmitBtn.CommandName = "Update";
            SubmitBtn.Text = "Cập nhật tài khoản";
        }

        protected void SubmitBtn_Command(object sender, CommandEventArgs e)
        {
            if ("Update".Equals(e.CommandName))
            {
                int accID = 0;
                try { accID = Int32.Parse(txtID.Text); }
                catch (Exception) { }
                AccountBLO accBLO = new AccountBLO();
                accBLO.UpdateAccount(accID, txtEmail.Text, txtName.Text, txtPass.Text, ddlRoles.SelectedValue);
                Response.Redirect(Resource.AccountList);
                return;
            }
            else if ("Create".Equals(e.CommandName))
            {
                AccountBLO accBLO = new AccountBLO();
                bool success = accBLO.AddNewAccount(txtEmail.Text, txtPass.Text, txtName.Text, ddlRoles.SelectedValue);
                if (!success)
                {
                    txtError.Visible = true;
                    return;
                }
                Response.Redirect(Resource.AccountList);
            }
        }
    }
}